// index.js

const dateFormat=require('../../utils/util.js')

Page({
  data: {
    // 当前扫描到的数据
    nowScanData:'',
    // 历史记录
    historyList:[]

  },

  onLoad(){
    wx.getStorage({
      key: 'historyList',
      success :(res)=> {
        this.setData({
          historyList:res.data || []
        })
      }
    })
  },

  // 扫一扫按钮
  scan(){
    wx.scanCode({
      success: (res)=> {
        wx.vibrateShort({
          type:'medium'
        })
        const time = Date.now()
        this.setData({
          nowScanData: res.result,
          historyList: [{
            time,
            date: this.dateFormat(time),
            content: res.result
          }].concat(this.data.historyList)
        })
        wx.setStorage({
          key:"historyList",
          data:this.data.historyList
        })
      }
    })
  },

  // 清空历史记录
  clearAll(){
    wx.showModal({
      title: '提示',
      content: '确认清空全部历史记录？',
      success: (res)=> {
        if (res.cancel) return

        this.setData({
          historyList:[],
          nowScanData:''
        })
        wx.removeStorage({
          key: 'historyList',
        })
      }
    })
  },

  // 当前扫描的清空
  nowClear(){
    this.setData({
      nowScanData:''
    })
  },

  // 复制当前扫描的内容
  nowCopy(){
    wx.setClipboardData({
      data: this.data.nowScanData,
    })
  },

  // 历史记录单项删除
  itemClear(e){

    wx.showModal({
      title: '提示',
      content: '确认删除这一条记录？',
      success: (res)=> {
        if (res.cancel) return

        const index = Number(e.currentTarget.dataset.index)
        this.data.historyList.splice(index,1)

        this.setData({
          historyList: this.data.historyList
        })
        wx.setStorage({
          key:"historyList",
          data:this.data.historyList
        })
      }
    })
  },

  // 历史记录单项拷贝
  itemCopy(e){
    const data = e.currentTarget.dataset.data
    wx.setClipboardData({
      data
    })
  },

  // 生成二维码
  createQR(e){
    const data = e.currentTarget.dataset.data
    wx.navigateTo({
      url:'../create/index?data=' + encodeURIComponent(data),
    })
  },

  // 时间转换
  dateFormat(date){
    return dateFormat.dateFormat(date, 'yyyy-MM-dd hh:mm:ss')
  },

  // 分享
  onShareAppMessage(){
    return{
      imageUrl:"./../../assets/logo.png"
    }
  }


})
